package org.flashIso.engine.core {
	import flash.display.MovieClip;
	import flash.events.Event;
	
	import org.flashIso.engine.events.IsoEvent;

	/**
	 * @author Marius Dorin Moraru
	 */
	public class ValidateQue {
		private static var _movieClip : MovieClip;
		
		private static var _invalidatedObjects : Array = new Array();
		
		private static function enterFrame(e : Event = null) : void {
			while (_invalidatedObjects.length > 0) {
				if (IValidateable(_invalidatedObjects[0]).invalidated == true){
					IValidateable(_invalidatedObjects[0]).validateNow();
					IValidateable(_invalidatedObjects[0]).invalidated = false;
					IValidateable(_invalidatedObjects[0]).dispatchEvent(new Event(Event.CHANGE));
				}
				_invalidatedObjects.shift();
			}
		}

		private static function init() : void {
			if (_movieClip == null) {
				_movieClip = new MovieClip();
				_movieClip.addEventListener(Event.ENTER_FRAME, enterFrame, false, 0, true);
			}
		}

		
		public static function add(object : IValidateable) : void {
			init();
			if (object.atomicValidation){
				object.validateNow();
				object.dispatchEvent(new Event(Event.CHANGE));
				object.invalidated = false;
			}else
			if (_invalidatedObjects.indexOf(object) < 0) {
				object.invalidated = true;
				_invalidatedObjects.push(object);
			}
			
		}
		public static function validateAll() :void {
			enterFrame();
		}
	}
}
